import {
	login,
	getUserInfo,
	addUser
} from '@/api/user'

const user = {
	state: {
		userID: uni.getStorageSync('userID') || '',
		auth: false,
		userInfo: JSON.parse(uni.getStorageSync('userInfo') || '{}'),
		wxUserInfo:JSON.parse(uni.getStorageSync('userInfo') || '{}'),
		token: uni.getStorageSync('token') || '',
		phone: uni.getStorageSync('phone') || '',
	},
	mutations: {
		SET_USER_INFO: (state, userInfo) => {
			state.userInfo = userInfo
			state.auth = true
		},
		SET_USER_ID: (state, userID) => {
			state.userID = userID
			uni.setStorageSync('userID', userID)
		},
		SET_USER_AUTH: (state, bool) => {
			state.auth = bool
		},
		SET_WX_USER_INFO: (state, data) => {
			state.wxUserInfo = data
			state.auth = true
		},
		SET_USER_PHONE: (state, data) => {
			state.phone = data
			uni.setStorageSync('phone', data)
		},
		SET_TOKEN: (state, data) => {
			state.token = data 
			uni.setStorageSync('token', data)
		},
		CLEAR_STATE: (state) => {
			state.userID = ''
			state.auth = false
			state.userInfo = {}
			state.wxUserInfo = {}
			state.token = ''
			state.phone = ''
		}
	},
	actions: {
		// 获取用户id
		Login({
			commit
		}, params) {
			return new Promise((resolve, reject) => {


				uni.login({
					provider: "weixin",
					success: async (res) => {
						uni.setStorageSync('loginCode', res.code)
						if (res.code) {
							params.weixinCode = res.code
							const result = await login(params)
							if (result.flag) {
								commit('SET_USER_ID', result.result.userId)
								commit('SET_USER_PHONE', params.name)
								commit('SET_TOKEN', result.result.checkToken)


								resolve(result)
							} else {
								reject(result)
							}
						}
					},
					fail: function() {
						uni.showToast({
							title: "微信登录失败",
							icon: "none",
						});
					},
				});

			})
		},
		// 获取用户信息
		GetUserInfo({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				getUserInfo(params)
					.then((res) => {
						const resData = JSON.parse(res.data)
						commit('SET_USER_INFO', resData.Records[0])
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 添加用户信息
		AddUser({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				addUser(params)
					.then((res) => {
						commit('SET_USER_AUTH', true)
						resolve(res)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		setWxUserINfo({
			commit
		}, data) {
			commit('SET_WX_USER_INFO', data)
		},
		// 退出清除数据
		clearUserInfo({
			commit
		}) {
			console.log('clear')
			commit('CLEAR_STATE')
		}
	},
	getters: {
		userInfo: (state) => state.userInfo,
		wxUserInfo: (state) => state.wxUserInfo,
		auth: (state) => state.auth,
		userID: (state) => state.userID,
		phone: (state) => state.phone,
		token: (state) => state.token,
	},
}

export default user
